﻿using System.Globalization;
using System.IdentityModel.Tokens.Jwt;

namespace daonaite.api.extends
{
    public class JwtMiddleware
    {
        private readonly RequestDelegate _next;

        public JwtMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {

            var token = context.Request.Headers.Authorization;
            if (token.Count > 0)
            {
                var tk = token.ToString().Replace("Bearer ", "");
                var handler = new JwtSecurityTokenHandler();
                var payload = handler.ReadJwtToken(tk).Payload;
                var claims = payload.Claims;

                var claim = claims.FirstOrDefault(x => x.Type == "userid");
                if (claim != null)
                {
                    context.Request.Headers.Append("loginuser", claim.Value);
                }

            }



            // Call the next delegate/middleware in the pipeline.
            await _next(context);
        }
    }
}
